package com.igoal.admin.web;

import java.io.File;
import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.igoal.admin.web.model.AdminBaseModel;
import com.igoal.dto.NewsDTO;
import com.igoal.service.NewsManager;
import com.igoal.utils.ImageUtils;
import com.igoal.web.validator.AddNewsValidator;

@Controller
public class AddNewsController extends AdminBaseController{
	private static final Log logger = LogFactory.getLog(AddNewsController.class);
	
	@Autowired
	AddNewsValidator addNewsValidator;
	
	@Autowired
	NewsManager newsManager;
	
	public AddNewsController() {
		logger.info("Initializing add news ...");
	}
	
	@RequestMapping(method=RequestMethod.GET, value="/admin/addNews.html")
	public String showForm(ModelMap modelMap){
		NewsDTO news = new NewsDTO();
		news.setCommentCount(0);
		news.setIndex(1);
		
		modelMap.addAttribute("news", news);
		
		return getViewPrefix() + "addNews";
	}
	
	@RequestMapping(method=RequestMethod.GET, value="/admin/editNews.html")
	public String showEditForm(ModelMap modelMap, @RequestParam("id") Long id){
		if(id == null || id < 0L){
			return "redirect:/admin/addNews.html";
		}
		
		NewsDTO news = newsManager.loadNews(id);
		if(news == null){
			return "redirect:/admin/addNews.html";
		}
		
		modelMap.addAttribute("news", news);
		
		return getViewPrefix() + "addNews";
	}
	
	@RequestMapping(method=RequestMethod.POST, value="/admin/editNews.html")
	public String submitUpdateForm(@ModelAttribute("news") NewsDTO news, BindingResult bindingResult, @RequestParam("avatarFile") MultipartFile avatarFile, HttpServletRequest request){
		String username = getUserInSession();
		
		addNewsValidator.validate(news, bindingResult);
		
		if(bindingResult.hasErrors()){			
			return getViewPrefix() + "addNews";
		}
		
		String avatar = writeAvatarFile(avatarFile, request);
		if (avatar != null) {
			news.setAvatar(avatar);
		}

		news = newsManager.updateNews(username, news);
		
		return "redirect:/newsDetails.html?id="+news.getId();
	}
	
	@RequestMapping(method=RequestMethod.POST, value="/admin/addNews.html")
	public String submitForm(@ModelAttribute("news") NewsDTO news, BindingResult bindingResult, @RequestParam("avatarFile") MultipartFile avatarFile, HttpServletRequest request){
		String username = getUserInSession();
		
		addNewsValidator.validate(news, bindingResult);
		
		if(bindingResult.hasErrors()){
			return getViewPrefix() + "addNews";
		}
		
		String avatar = writeAvatarFile(avatarFile, request);
		if (avatar != null) {
			news.setAvatar(avatar);
		}

		news = newsManager.addNews(username, news);
		return "redirect:/newsDetails.html?id="+news.getId();
	}
	
	String writeAvatarFile(MultipartFile avatarFile, HttpServletRequest request) {
		if (avatarFile != null) {
			try {
				String serverPath = getServerPath(request);
				String repository = File.separator + "files" + File.separator + "_news_" + File.separator;
				String tmpDir = File.separator + "tmp";
				String name = Calendar.getInstance().getTime().getTime() + avatarFile.hashCode() + "";
				String tmpOutput = tmpDir + File.separator + name + getFileExtension(avatarFile.getOriginalFilename());
				String finalRepositoryPath = repository + name + getFileExtension(avatarFile.getOriginalFilename());
				String finalOutput = serverPath + finalRepositoryPath;
				File tmpOutputFile = new File(tmpOutput);
				File repositoryDir = new File(serverPath + repository);
				if(!repositoryDir.exists()){
					repositoryDir.mkdirs();
				}

				avatarFile.transferTo(tmpOutputFile);
				ImageUtils.scaleImageWidth(tmpOutput, finalOutput, 170);
				
				if(finalRepositoryPath.indexOf("\\") >= 0){
					// for windows env
					finalRepositoryPath = finalRepositoryPath.replaceAll("\\\\", "/");
				}
				return finalRepositoryPath;
			} catch (Exception e) {
				logger.error(e);
			}
		}

		return null;
	}

	public String getServerPath(HttpServletRequest request) {			
		String serverPath = request.getSession().getServletContext().getRealPath("");
		serverPath = serverPath.replace(File.separator + "ROOT", "");
		return serverPath;
	}

	public String getFileExtension(String filenameExtension) {
		int dotPos = filenameExtension.lastIndexOf(".");
		String extension = filenameExtension.substring(dotPos);
		return extension;
	}

	@Override
	public void initLeftPage(AdminBaseModel model, HttpServletRequest request) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void initRightPage(AdminBaseModel model, HttpServletRequest request) {
		// TODO Auto-generated method stub
		
	}
}
